import axios from "axios";
import router from "../router/index";
import common from "../utils/common"
import {
	saveAs
} from 'file-saver'
import moment from "moment"
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

NProgress.configure({
	showSpinner: false
});

// 创建axios实例
const service = axios.create({
	// axios中请求配置有baseURL选项，表示请求URL公共部分
	baseURL: import.meta.env.VITE_APP_BASE_API,
	// 超时
	timeout: 10000,
	headers: {
		"client": "admin",
		"X-Requested-With": 'XMLHttpRequest',
		"withCredentials": false,
		"Content-Type": 'application/json;charset=utf-8'
	}
})

const upFileUrl = "/server/api/app/file/up"
const uploadHeaders = () => {
	return {
		client: 'admin',
		authorization: getToken(),
	}
}
/**
 * 获取token
 */
function getToken() {
	let token = localStorage.getItem("token")
	if (token) {
		return "Bearer_" + token
	} else {
		return "";
	}
}

// http request 拦截器
service.interceptors.request.use(
	config => {
		console.info("request拦截器", config)
		NProgress.start();
		//设置token
		config.headers['authorization'] = getToken();
		return config;
	},
	error => {
		Nprogress.done()
		common.msgError(error.message)
		return Promise.reject(error);
	}
);

//http response拦截器
service.interceptors.response.use(
	response => {
		// 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
		// 否则的话抛出错误
		console.info("response拦截器", response)
		NProgress.done()
		let config = response.config
		let responseType = response.config.responseType
		//处理下载文件
		if (responseType == 'blob') {
			let blob = new Blob([response.data]);
			let fileName = JSON.parse(config.data).fileName
			if (fileName) {
				fileName = `${getNoType(fileName)}_${moment().format('YYYYMMDDHHmmss')}.` + getType(fileName)
			} else {
				fileName = moment().format('YYYYMMDDHHmmss')
			}

			saveAs(blob, decodeURI(fileName))
			return Promise.resolve(response);
		}
		//请求成功
		if (response.status === 200) {
			let result = response.data
			let code = result.code
			if (code == 200) {
				if (config.method == 'post' || config.method == 'put' || config.method == 'delete') {
					common.msgSuccess("操作成功")
				}
				return Promise.resolve(result.result);
			} else {
				let isErrorToast = true
				if (config.hasOwnProperty('isErrorToast')) {
					isErrorToast = config.isErrorToast
				}
				if (code == 401) {
					if (router.currentRoute.path != '/login') {
						//清除storage中数据
						localStorage.clear();
						sessionStorage.clear();
						//跳转登录页
						router.replace("/login");
					}
					if (isErrorToast) {
						common.msgWarn(result.message)
					}
				} else if (result.code == 500) {
					//系统错误
					if (isErrorToast) {
						common.msgError(result.message)
					}
				} else if (result.code == 301) {
					//警告
					if (isErrorToast) {
						common.msgWarn(result.message);
					}
				}else{
					if (isErrorToast) {
						common.msgWarn(result.message);
					}
				}
				return Promise.reject(result.message);
			}
		} else {
			return Promise.reject(response);
		}
	},
	error => {
		NProgress.done()
		console.info("response", error)
		common.msgError(error.message)
		return Promise.reject(error);
	}
);

function getType(fileName) {
	let index = fileName.lastIndexOf(".");
	let ext = fileName.substr(index + 1);
	return ext.toLowerCase();
}

function getNoType(fileName) {
	let index = fileName.lastIndexOf(".");
	let ext = fileName.substr(0, index);
	return ext.toLowerCase();
}

//get请求
function get(url, params, config) {
	config = config ? config : {}
	return service.get(url, {
		params: params
	}, config)
}
//post请求
function post(url, params, config) {
	config = config ? config : {}
	return service.post(url, params, config);
}
//put请求
function put(url, params, config) {
	config = config ? config : {}
	return service.put(url, params, config)
}
//put请求
function del(url, params, config) {
	config = config ? config : {}
	return service.delete(url, {
		params: params
	}, config)
}
//下载
function download(url, params, config) {
	config = config ? config : {},
	config.responseType = 'blob'
	return service.post(url, params, config)
}
// 上传
function upload(url, params, config) {
	const formData = new FormData()
	for (let key in params) {
		formData.append(key, params[key])
	}
	config = config ? config : {}
	if(!config.headers){
		config.headers = {
			'Content-Type':""
		}
	}
	config.headers['Content-Type'] = 'multipart/form-data'
	return service.post(url, formData, config)
}

export default {
	name: "http",
	upFileUrl: upFileUrl,
	getToken: getToken,
	uploadHeaders: uploadHeaders,
	get,
	post,
	put,
	delete:del,
	download,
	upload
};